package com.fs.service.bo.purchase;

import com.fs.entity.PurchaseState;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

public class StatusTypeHandler extends BaseTypeHandler<Status> {

    private static final String BEGIN_TIME_LABEL = "begin_time";
    private static final String END_TIME_LABEL = "end_time";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Status parameter, JdbcType jdbcType) throws SQLException {
        System.out.println(parameter);
    }

    @Override
    public Status getNullableResult(ResultSet rs, String columnName) throws SQLException {
        LocalDateTime beginTime= rs.getTimestamp(BEGIN_TIME_LABEL).toLocalDateTime();
        LocalDateTime endTime= rs.getTimestamp(END_TIME_LABEL).toLocalDateTime();
        PurchaseState state = Enum.valueOf(PurchaseState.class, rs.getString(columnName));
        return Status.transfer(state, beginTime, endTime);

    }

    @Override
    public Status getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        LocalDateTime beginTime= rs.getTimestamp(BEGIN_TIME_LABEL).toLocalDateTime();
        LocalDateTime endTime= rs.getTimestamp(END_TIME_LABEL).toLocalDateTime();
        PurchaseState state = Enum.valueOf(PurchaseState.class, rs.getString(columnIndex));
        return Status.transfer(state, beginTime, endTime);
    }

    @Override
    public Status getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        LocalDateTime beginTime= cs.getTimestamp(BEGIN_TIME_LABEL).toLocalDateTime();
        LocalDateTime endTime= cs.getTimestamp(END_TIME_LABEL).toLocalDateTime();
        PurchaseState state = Enum.valueOf(PurchaseState.class, cs.getString(columnIndex));
        return Status.transfer(state, beginTime, endTime);
    }
}
